$(document).ready(function () {
    //$(window).bind("beforeunload", function () { return "Do you really want to close?"; });
    function getCookie(c_name) {
        var i, x, y, ARRcookies = document.cookie.split(";");
        for (i = 0; i < ARRcookies.length; i++) {
            x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
            y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
            x = x.replace(/^\s+|\s+$/g, "");
            if (x == c_name) {
                return unescape(y);
            }
        }
    }
    function deparam(params) {
        var o = {};
        if (!params) return o;
        var a = params.split('&');
        for (var i = 0; i < a.length; i++) {
            var pair = a[i].split('=');
            o[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
        }
        return o;
    }
    $("#dialog:ui-dialog").dialog("destroy");
    $(".editor").hide();
    $("#loadingDialog").dialog({
        open: function (event, ui) { $(".ui-dialog-titlebar-close").hide(); },
        autoOpen: true,
        modal: true
    });
    //begin "Switching Question List and Editor Area"
    $("#questionList").animate({ width: "toggle" }, 0);

    $("#toggleBar").click(function () {
        $("#editorArea").animate({ width: "toggle" }, "medium");
        $("#questionList").animate({ width: "toggle" }, "medium");
        ResetQuestionList();
    });
    //end "Switching Question List and Editor"

    //Begin Load data
    answerList = new Array();
    questionOrder = new Array();
    currentQuestion = 0;
    notDoneYet = new Array();
    timeLeft = 1;
    timeSpend = 0;
    var query = "/QuizService.svc/Exercises(" + ExId + ")";
    $.getJSON(query, function (result) {
        questionList = $.parseJSON(result.d.ExContent);
        for (i = 0; i < questionList.length; i++) {
            var ansOrder = new Array();
            for (j = 0; j < questionList[i].numAns; j++) {
                ansOrder.push(j);
            }
            ansOrder.sort(function () { return 0.5 - Math.random() });
            questionList[i].ansOrder = ansOrder;
        }
        for (i = 0; i < questionList.length; i++) {
            questionOrder.push(i);
        }
        questionOrder.sort(function () { return 0.5 - Math.random() });
        ChangeQuestion(questionOrder[0]);
        $("#loadingDialog").dialog("destroy");
        ResetQuestionList();
        if (result.d.ExTime != null) {
            timeLeft = result.d.ExTime * 60;
            var coutingDown = window.setInterval(function () {
                timeLeft--;
                timeSpend++;
                hLeft = Math.floor(timeLeft / 3600);
                mLeft = Math.floor((timeLeft - (hLeft * 3600)) / 60);
                sLeft = timeLeft - (mLeft * 60) - (hLeft * 3600);
                if (timeLeft == 0) {
                    coutingDown = window.clearInterval(coutingDown);
                    $("#buttonSubmit").click();
                }
                $("#sLeft").text(sLeft);
                $("#mLeft").text(mLeft);
                $("#hLeft").text(hLeft);
            }, 1000);
        } else {
            var coutingDown = window.setInterval(function () {
                timeSpend++;
            });
            $("#countDown").hide();
        }
    }).fail(function () { $("#loadingDialog").html('<span style="color:red;">Error....</span>'); });

    $("#ansListType2A").sortable({
        cancel: ".ui-state-disabled"
    });
    $("#ansListType2B").sortable({
        update: function (event, ui) {
            questionList[questionOrder[currentQuestion]].checked = true;
            questionList[questionOrder[currentQuestion]].answer = new Array();
            questionList[questionOrder[currentQuestion]].answer = $(this).sortable('toArray');
        }
    });

    $("#buttonBack").click(function () {
        if (currentQuestion == 0) {
            currentQuestion = questionList.length - 1;
            ChangeQuestion();
        } else {
            currentQuestion--;
            ChangeQuestion();
        }
    });

    $("#buttonNext").click(function () {
        if (currentQuestion == (questionList.length - 1)) {
            currentQuestion = 0;
            ChangeQuestion();
        } else {
            currentQuestion++;
            ChangeQuestion();
        }
    });

    $(".quesTitle").live("click", function () {
        currentQuestion = parseInt($(this).attr("dataIndex"));
        ChangeQuestion();
        $("#editorArea").animate({ width: "toggle" }, "medium");
        $("#questionList").animate({ width: "toggle" }, "medium");
    });
    $("#buttonSubmit").click(function () {
        notDoneYet = new Array();
        for (i = 0; i < questionOrder.length; i++) {
            if (typeof questionList[questionOrder[i]].checked == "undefined") {
                notDoneYet.push(i);
                continue;
            }
            if (questionList[questionOrder[i]].checked == false) {
                notDoneYet.push(i);
            }
        }
        var submitNow = true;
        if (notDoneYet.length > 0 && timeLeft != 0) {
            submitNow = false;
            submitNow = confirm("Some question are not answered, check the question list for detail.\n Are you really want to submit?");
        }
        if (submitNow) {
            for (i = 0; i < questionList.length; i++) {
                answerList.push(questionList[i].answer);
            }
            ansList = new Object();
            ansList.ExId = ExId;
            ansList.Ans = answerList;
            ansList.TimeSpend = timeSpend;
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "/Quiz/GetResult/",
                data: JSON.stringify(ansList),
                success: function (data) {
                    var re = $.parseJSON(data);
                    $("#loadingDialog").empty();
                    $("#loadingDialog").append("<h1>" + re.Point + "/" + re.Total + "</h1>");
                    $("#loadingDialog").dialog({
                        close: function (event, ui) {
                        },
                        modal: true
                    });
                }
            });
        }
    });

    $("input.type0Radio").live("change", function () {
        questionList[questionOrder[currentQuestion]].checked = true;
        questionList[questionOrder[currentQuestion]].answer = new Array();
        questionList[questionOrder[currentQuestion]].answer.push($("input.type0Radio:checked").val());
    });

    $("input.type1CheckBox").live("change", function () {
        questionList[questionOrder[currentQuestion]].checked = true;
        questionList[questionOrder[currentQuestion]].answer = new Array();
        $("input.type1CheckBox:checked").each(function () {
            questionList[questionOrder[currentQuestion]].answer.push($(this).val());
        });
    });

    $("input.type3Text").live("change", function () {
        questionList[questionOrder[currentQuestion]].checked = true;
        questionList[questionOrder[currentQuestion]].answer = new Array();
        $("input.type3Text").each(function () {
            questionList[questionOrder[currentQuestion]].answer.push($(this).val());
        });
    });

    $("#answerType4").keypress(function () {
        var words = $.trim($(this).val()).split(" ");
        questionList[questionOrder[currentQuestion]].answer = new Array();
        questionList[questionOrder[currentQuestion]].answer.push($(this).val());

        $("#answerType4Len").text(words.length);

        if (words.length >= questionList[questionOrder[currentQuestion]].min &&
        words.length <= questionList[questionOrder[currentQuestion]].max) {
            questionList[questionOrder[currentQuestion]].checked = true;
            $("#answerType4Len").attr("style", "color : inherit;");
        } else {
            questionList[questionOrder[currentQuestion]].checked = false;
            $("#answerType4Len").attr("style", "color : red;");
        }
    });

    function ChangeQuestion() {
        $("#mainEditor").children().hide();
        var ques = questionList[questionOrder[currentQuestion]];

        $("#editorType" + ques.type).show();
        $("#questionType" + ques.type).text(ques.ques);

        var ans = new Array();

        if (typeof ques.answer != "undefined")
            ans = ques.answer;

        if (ques.type == 0) {
            $("#ansListType0").empty();
            for (i = 0; i < ques.numAns; i++) {
                $("#ansListType0").append('<li><input type="radio" class="type0Radio" name="ansList" value="' + ques.ansOrder[i] + '" ' + (ans[0] == ques.ansOrder[i].toString() ? 'checked="checked"' : '') + ' /><span>' + ques.ans[ques.ansOrder[i]] + '</span></li>');
            }
            //alert(ques.answer);
        } else if (ques.type == 1) {
            $("#ansListType1").empty();
            for (i = 0; i < ques.numAns; i++) {
                $("#ansListType1").append('<li><input type="checkbox" class="type1CheckBox" value="' + ques.ansOrder[i] + '" ' + (jQuery.inArray(ques.ansOrder[i].toString(), ans) > -1 ? 'checked="checked"' : '') + ' /><span>' + ques.ans[ques.ansOrder[i]] + '</span></li>');
            }
        } else if (ques.type == 2) {
            $("#ansListType2A").empty();
            $("#ansListType2B").empty();

            for (i = 0; i < ques.numAns; i++) {
                $("#ansListType2A").append('<li class="ui-state-disabled">' + ques.ansA[i] + '</li>');
            }
            if (ans.length == 0) {
                for (i = 0; i < ques.numAns; i++) {
                    $("#ansListType2B").append('<li id="' + ques.ansOrder[i] + '">' + ques.ansB[ques.ansOrder[i]] + '</li>');
                }
            } else {
                for (i = 0; i < ans.length; i++) {
                    $("#ansListType2B").append('<li id="' + ans[i] + '">' + ques.ansB[parseInt(ans[i])] + '</li>');
                }
            }
        } else if (ques.type == 3) {
            $("#ansListType3").empty();
            for (i = 0; i < ques.numAns; i++) {
                $("#ansListType3").append((i + 1) + ':<input type="text" class="type3Text" ' + (typeof ans[i] != "undefined" ? 'value="' + ans[i] + '"' : '') + ' /><br />');
            }
            var txt = $("#questionType3").text();
            var i = 1;
            while (txt.indexOf("***") > -1) {
                txt = txt.replace("***", "___[" + i +"]");
                i++;
            }
            $("#questionType3").text(txt);
        } else if (ques.type == 4) {
            $("#answerType4LenMin").text(ques.min);
            $("#answerType4LenMax").text(ques.max);
            if (typeof ans[0] == "undefined")
                $("#answerType4").val("");
            else
                $("#answerType4").val(ans[0]);
        }
    }

    function ResetQuestionList() {
        $("#questionList").empty();
        for (i = 0; i < questionOrder.length; i++) {
            var ques = questionList[questionOrder[i]];
            var quesDiv = $('<div class="quesTitle Type' + ques.type + '" dataType="' + ques.type + '" dataIndex="' + i + '"></div>').append('<span class="quesTitleText">' + ques.ques + '</span>');
            if (typeof ques.checked != "undefined")
                if (ques.checked == true)
                    quesDiv.append('<span class="ui-icon ui-icon-check" title="ui-icon-check">&nbsp;</span>');
            $("#questionList").append(quesDiv);
        }
    }
});